// 创建express服务器
const express = require('express');
const app = express();
// const router = require('./router/user/register')
// const routerLogin = require('./router/user/login')
const main = require('./router/main')
const jwt = require('jsonwebtoken')
require('./db/db')

app.use(express.urlencoded({extended:false}))

// app.use('/api', router)
// app.use('/api', routerLogin)
app.use('/api', main)

// 设置跨域和相应数据格式  
app.all('*', function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*')
    res.header('Access-Control-Allow-Headers', 'X-Requested-With, mytoken')
    res.header('Access-Control-Allow-Headers', 'X-Requested-With, Authorization')
    res.setHeader('Content-Type', 'application/json;charset=utf-8')
    res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization, Accept,X-Requested-With')
    res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
    res.header('X-Powered-By', ' 3.2.1')
    if (req.method == 'OPTIONS') res.send(200)
    /*让options请求快速返回*/ else next()
})

app.get('/',(req,res) => {
    res.send({
        data:null,
        meta:{
            msg:'Not Found',
            status:404
        }
    })
})
app.use('/api',(req,res,next) => {
    if(req.url == '/login' || req.url == '/register') {
        next()
        return
    }
    // 接收客户端传过来的token
    const token = String(req.headers.authorization)
    // 解析 token 如果解析失败 返回的是null
    
    const username = jwt.decode(token,'keqing')
    // 判断客户端是否传递token
    if(token == 'undefined' || username == null ) {
        res.status(400).send({
            data:null,
            meta: {
                msg:"token无效",
                status:400
            }
        })
        return
    }
    // 直接放行
    next()
    // res.send('ok')
})


// 监听3000 端口
app.listen(3000,function(){
    console.log('正在监听3000端口...');
})